package com.oo.app.utils;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.view.View;


import com.oo.app.base.Constants;
import com.oo.app.ui.bean.UserInfo;

import net.oschina.common.helper.SharedPreferencesHelper;


/**
 * 账户辅助类，
 * 用于更新用户信息和保存当前账户等操作
 */
public final class AccountHelper {
    private static final String TAG = AccountHelper.class.getSimpleName();
    private UserInfo user;
    private Application application;
    @SuppressLint("StaticFieldLeak")
    private static AccountHelper instances;

    private AccountHelper(Application application) {
        this.application = application;
    }

    public static void init(Application application) {
        if (instances == null)
            instances = new AccountHelper(application);
        else {
            // reload from source
            instances.user = SharedPreferencesHelper.loadFormSource(instances.application, UserInfo.class);

        }
    }

    public static boolean isLogin() {
        return Integer.parseInt(getUserId()) > 0;
    }

    public static String getUserId() {
        return getUser().getUserId();
    }


    public static String getToken() {
        return getUser().getToken();
    }

    public synchronized static UserInfo getUser() {
        if (instances == null) {
            return new UserInfo();
        }
        if (instances.user == null)
            instances.user = SharedPreferencesHelper.loadFormSource(instances.application, UserInfo.class);
        if (instances.user == null)
            instances.user = new UserInfo();
        return instances.user;
    }

    public static boolean updateUserCache(UserInfo user) {
        if (user == null)
            return false;
        instances.user = user;
        return SharedPreferencesHelper.save(instances.application, user);
    }

    private static void clearUserCache() {
        instances.user = null;
        SharedPreferencesHelper.remove(instances.application, UserInfo.class);
    }

    public static boolean login(final UserInfo user) {
                int count = 10;
        boolean saveOk;
        // 保存缓存
        while (!(saveOk = updateUserCache(user)) && count-- > 0) {
            SystemClock.sleep(100);
        }

        if (saveOk) {
            // 登录成功
        }
        return saveOk;
    }

    /**
     * 退出登陆操作需要传递一个View协助完成延迟检测操作
     *
     * @param view     View
     * @param runnable 当清理完成后回调方法
     */
    public static void logout(final View view, final Runnable runnable) {
        // 清除用户缓存
        clearUserCache();
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                view.removeCallbacks(this);
                UserInfo user = SharedPreferencesHelper.load(instances.application, UserInfo.class);
                // 判断当前用户信息是否清理成功
                if (user == null || Integer.parseInt(user.getUserId()) <= 0) {
                    clearAndPostBroadcast(instances.application);
                    runnable.run();
                } else {
                    view.postDelayed(this, 200);
                }
            }
        }, 200);
    }

    /**
     * 保存登陆信息
     * @param phone
     * @param password
     * @return
     */
    public static boolean saveLoginMes(String phone, String password) {
        SharedPreferences msp = instances.application.getSharedPreferences(Constants.USER, Context.MODE_PRIVATE);
        //获取到edit对象
        SharedPreferences.Editor edit = msp.edit();
        //通过editor对象写入数据
        edit.putString(Constants.PHONE,phone);
        edit.putString(Constants.PASSWORD,password);
        //提交数据存入到xml文件中
        boolean result = edit.commit();
        return result;
    }

    /**
     * 当前用户信息清理完成后调用方法清理服务等信息
     *
     * @param application Application
     */
    private static void clearAndPostBroadcast(Application application) {
//        // 清理网络相关
//        ApiHttpClient.destroyAndRestore(application);
//
//        // Logout 广播
//        Intent intent = new Intent(Constants.INTENT_ACTION_LOGOUT);
//        application.sendBroadcast(intent);
    }
}
